package cn.edu.fjnu.camera;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import cn.edu.fjnu.camera.R;

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Bitmap.Config;
import android.hardware.Camera;
import android.hardware.Camera.PictureCallback;
import android.net.Uri;
import android.os.Bundle;
import android.os.Debug;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.OrientationEventListener;
import android.view.SurfaceHolder;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.Toast;

public class CameraSticker extends Activity implements View.OnClickListener,
		SurfaceHolder.Callback {

	// Log TAG
	private static final String TAG = "CameraSticker";

	private byte[] mbyte;

	private boolean temp = false;// 判断有没有重新选择大头贴

	private String name = "false"; // 判断是不是可以移动的图片

	private SharedPreferences mPrefs;
	// 由于采用FreamLayout，采用改变量判断页面状态
	private static final int START_PAGE = 1;
	private static final int CAMERA_PREVIEW_PAGE = 2;
	private static int mViewStatus = START_PAGE;

	private static final int GET_STICKER_IMAGE = 0;
	private static final int GET_IMAGE = 1;
	// The windows DisplayMetrics
	private int intScreenX;
	private int intScreenY;
	// The orientation of screen
	private static final int PORTRAIT = Configuration.ORIENTATION_PORTRAIT;
	private static final int LANDSCAPE = Configuration.ORIENTATION_LANDSCAPE;
	// The storage remaining space
	private int mPicturesRemaining;
	private Menu mMenu;

	// Message type
	private static final int RESTART_PREVIEW = 3;
	private static final int CLEAR_SCREEN_DELAY = 4;
	private static final int OPEN_GALLERY = 5;
	private static final int UPDATE_STICKER = 6;
	private static final int VIEW_CLICK_FOCUS = 7;

	// Camera相关的对象和变量
	private Camera mCamera;
	private Camera.Parameters mParameters;
	private boolean mPreviewing = false;
	private boolean mPausing = false;
	private boolean mCameraMode; // 相机的拍摄模式，true为大头贴模式

	// Camera的相关参数
	private boolean mFocusMode;
	private String mWhiteBalance;
	private String mAntiBanding;

	private CameraPreview mSurfaceView;
	private SurfaceHolder mSurfaceHolder;
	// 捕捉对象
	private Capturer mCaptureObject;
	private ImageCapture mImageCapture = null;

	// Camera的一些回调接口实例
	// @SuppressWarnings("unused")
	private ShutterCallback mShutterCallback = new ShutterCallback();
	private RawPictureCallback mRawPictureCallback = new RawPictureCallback();
	private AutoFocusCallback mAutoFocusCallback;
	private long mRawPictureCallbackTime;

	// Camera Status Value, it is import to change the value when do operation
	// to the Camera
	private static final int IDLE = 1;
	private static final int SNAPSHOT_IN_PROGRESS = 2;
	private static final int SNAPSHOT_COMPLETED = 3;

	private int mOriginalViewFinderWidth, mOriginalViewFinderHeight;
	private int mViewFinderWidth, mViewFinderHeight;

	private boolean mKeepAndRestartPreview;
	private static int mStatus = IDLE;

	private OrientationEventListener mOrientationListener;
	private int mLastOrientation = Configuration.ORIENTATION_UNDEFINED;

	private MoveImageView stickerPhoto;
	private Bitmap bmpScaleSticker; // 缩放后的大头贴图片

	private RelativeLayout relative_startpage; // 开始界面
	private RelativeLayout relative_camerasticker; // 大头贴拍摄界面

	// Picture save path
	private static final String CAPTUREFILEPATH = "/sdcard/DCIM/100MEDIA/";

	// private View.OnTouchListener onTouchListener;
	private MainHandler mHandler = new MainHandler();

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d(TAG, "onCreate");

		Thread openCameraServiceThread = new Thread(new Runnable() {
			public void run() {
				Log.d(TAG, "openCameraServiceThread run");
				mCamera = Camera.open();
				mParameters = mCamera.getParameters();
				mParameters.set("jpeg-quality", 85);
			}
		});
		// Start the Thread
		openCameraServiceThread.start();

		// FullScreen Mode
		getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
		// Windows No title
		requestWindowFeature(Window.FEATURE_NO_TITLE);

		setContentView(R.layout.camerasticker);
		// 初始化控件
		iniwidget();
		// 初始化控件响应事件
		iniwidgetlistener();

		mPrefs = PreferenceManager.getDefaultSharedPreferences(this);

		// 等待openCameraServiceThread线程结束
		try {
			openCameraServiceThread.join();
			Log.d(TAG, "CameraServiceEnd");
		} catch (InterruptedException ex) {

		}

	}

	// 初始化控件
	public void iniwidget() {
		// Setting the FrameLayout
		relative_startpage = (RelativeLayout) findViewById(R.id.rl_start_page);
		relative_camerasticker = (RelativeLayout) findViewById(R.id.rl_camerasticker);
		relative_startpage.setVisibility(View.VISIBLE);
		relative_camerasticker.setVisibility(View.GONE);
		ImageView image_normalmode = (ImageView) findViewById(R.id.mode_normal);
		ImageView image_stickermode = (ImageView) findViewById(R.id.mode_sticker);
		image_normalmode.setOnClickListener(this);
		image_stickermode.setOnClickListener(this);
		// bmpScaleSticker是缩放后的大头贴图片
		stickerPhoto = (MoveImageView) this.findViewById(R.id.sticker_photo);

		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);

		intScreenX = dm.widthPixels;
		intScreenY = dm.heightPixels;
		Log.d(TAG, "dm" + intScreenX + "dm" + intScreenY);

		Bitmap bmpSticker = BitmapFactory.decodeResource(CameraSticker.this
				.getResources(), R.drawable.frame_3);
		bmpScaleSticker = ImgUtil.AbsResizeBitmap(bmpSticker, intScreenX,
				intScreenY);
		mSurfaceView = (CameraPreview) findViewById(R.id.camera_preview);

	}

	// 初始化控件监听器
	public void iniwidgetlistener() {
		// 这里仅仅获得SurfaceHolder
		SurfaceHolder holder = mSurfaceView.getHolder();
		holder.addCallback(this);
		holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
		mOrientationListener = new OrientationEventListener(this) {
			@Override
			public void onOrientationChanged(int orientation) {// 监听方向改变
				if (orientation != ORIENTATION_UNKNOWN)
					mLastOrientation = orientation;
			}
		};
		ImageButton button_takePhoto = (ImageButton) findViewById(R.id.imageButton_takephoto);
		ImageButton button_openImageFile = (ImageButton) findViewById(R.id.imageButton_openimagefile);
		button_takePhoto.setOnClickListener(this);
		button_openImageFile.setOnClickListener(this);
	}

	// 实现View.OnClickListener的onClick方法
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.imageButton_takephoto:
			Log.d(TAG, "ImageButton_takephoto is clicked");
			doSnap();
			// restartPreview();
			break;
		case R.id.imageButton_openimagefile:
			Log.d(TAG, "ImageButton_openimagefile is clicked");
			openPictureGallery();
			break;
		case R.id.mode_normal:
			Log.d(TAG, "Normal Mode");
			// openHTCCamera();
			mCameraMode = false;
			startPreviewLayout();
			break;
		case R.id.mode_sticker:
			Log.d(TAG, "Sticker Mode");
			mCameraMode = true;
			startPreviewLayout();
			break;
		}
	}

	// 主界面到正常拍照和大头贴拍照的选择
	private void startPreviewLayout() {// 使预览页面可见
		relative_startpage.setVisibility(View.GONE);
		relative_camerasticker.setVisibility(View.VISIBLE);
		mHandler.sendEmptyMessage(UPDATE_STICKER);
		mViewStatus = CAMERA_PREVIEW_PAGE;

		if (mMenu != null) {
			if (mCameraMode == false) {
				mMenu.setGroupVisible(MenuHelper.STICKER_MODE_ITEM, false);
			} else {
				mMenu.setGroupVisible(MenuHelper.STICKER_MODE_ITEM, true);
			}
		}
	}

	// 重启预览
	private void restartPreview() {
		CameraPreview surfaceView = mSurfaceView;
		surfaceView.setAspectRatio(CameraPreview.DONT_CARE);
		// Just Test
		mStatus = IDLE;
		setViewFinder(mOriginalViewFinderWidth, mOriginalViewFinderHeight, true);
	}

	// Create Menu
	// onCreateOptiosMenu是在第一次点击Menu按钮是调用，这里需要处理两个模式下MenuItem的可见性
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {// onCreateOptiosMenu是在第一次点击Menu按钮是调用，这里需要处理两个模式下MenuItem的可见性
		Log.v(TAG, "Creating the menu");
		menu.add(MenuHelper.NORAML_MODE_ITEM, 1, Menu.NONE, "Pictures")
				.setIcon(R.drawable.ic_btn_actionmenu_gallery_default);
		menu.add(MenuHelper.STICKER_MODE_ITEM, 2, Menu.NONE, "Sticker")
				.setIcon(R.drawable.ic_menu_props);
		menu.add(MenuHelper.NORAML_MODE_ITEM, 3, Menu.NONE, "Setting").setIcon(
				R.drawable.ic_menu_preferences);

		if (mCameraMode == false)
			menu.setGroupVisible(MenuHelper.STICKER_MODE_ITEM, false);
		mMenu = menu;
		return super.onCreateOptionsMenu(menu);
	}

	// 对Menu被点选的响应事件
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		Log.d(TAG, "onOptionsItemSelected");
		switch (item.getItemId()) {
		case 1:
			// 打开手机内存中图片文件夹
			openPictureGallery();
			break;
		case 2:
			startActivityForResult(new Intent(this, StickerChoice.class),
					GET_STICKER_IMAGE);
			break;
		case 3:
			this.startActivity(new Intent(this, CameraSettings.class));
			break;
		}
		return true;
	}

	// 采用Handler机制来处理界面的响应
	private class MainHandler extends Handler {
		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case RESTART_PREVIEW:
				if (mStatus == SNAPSHOT_IN_PROGRESS) {
					mHandler.sendEmptyMessageAtTime(RESTART_PREVIEW, 100);
				} else if (mStatus == SNAPSHOT_COMPLETED) {
					// 重启预览
					mCaptureObject.dismissFreezeFrame();
				}
				break;
			case CLEAR_SCREEN_DELAY:
				getWindow().clearFlags(
						WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
				break;
			case OPEN_GALLERY:
				// CameraSticker.this.openPictureGallery();
				break;
			case UPDATE_STICKER:
				updateSticker();
				break;
			case VIEW_CLICK_FOCUS:

				break;
			}
		}
	}

	private interface Capturer {
		void onSnap();

		void dismissFreezeFrame();
	}

	private class ImageCapture implements Capturer {
		private boolean mCapturing = false;
		Bitmap mCaptureOnlyBitmap = null;

		public ImageCapture() {

		}

		public void onSnap() {
			if (mPausing == true)
				return;

			if (mStatus == SNAPSHOT_IN_PROGRESS
					|| mStatus == SNAPSHOT_COMPLETED) {
				Log.d(TAG, "mStatus Value:" + Integer.toString(mStatus));
				mKeepAndRestartPreview = true;
				mHandler.sendEmptyMessage(RESTART_PREVIEW);
				return;
			}
			mStatus = SNAPSHOT_IN_PROGRESS;
			mKeepAndRestartPreview = true;
			mImageCapture.initiate(true);
		}

		public void initiate(boolean captureOnly) {
			if (mCamera == null) {
				return;
			}
			mCapturing = true;
			Capture();
		}

		public void dismissFreezeFrame() {
			if (mStatus == SNAPSHOT_IN_PROGRESS) {
				// 仍然在处理拍照后保存
				// If we are still in the process of taking a picture, then just
				// post a message.
				mHandler.sendEmptyMessage(RESTART_PREVIEW);
			} else {
				restartPreview();
			}
		}

		public void storeImage(byte[] data, Camera camera) {
			Log.d(TAG, "storeImage");
			// Generate the bitmap from the camera buffer data
			Log.d(TAG, "storeImage" + data);
			// Bitmap bmpImage = BitmapFactory.decodeByteArray(data, 0,
			// data.length);
			Bitmap bmpImage = ImgUtil.Bytes2Bimap(data);
			Log.d(TAG, "BitmapFactory");
			if (mCameraMode == false)
				mCaptureOnlyBitmap = bmpImage;
			else
				mCaptureOnlyBitmap = CameraSticker.this.createStickerImage(
						bmpImage, bmpScaleSticker);
			long takeTime = System.currentTimeMillis();
			Log.d(TAG, "takeTime");
			File myCaptureFile = new File(CAPTUREFILEPATH
					+ String.valueOf(takeTime) + ".jpg");
			try {
				BufferedOutputStream bos = new BufferedOutputStream(
						new FileOutputStream(myCaptureFile));
				mCaptureOnlyBitmap
						.compress(Bitmap.CompressFormat.JPEG, 80, bos);

				bos.flush();
				bos.close();
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
			sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri
					.parse("file://"
							+ Environment.getExternalStorageDirectory())));
		}

		public void Capture() {// 捕捉图像
			mPreviewing = false;
			mCaptureOnlyBitmap = null;

			mCamera.takePicture(mShutterCallback, mRawPictureCallback,
					new JpegPictureCallback());
		}

		public Bitmap getLastBitmap() {
			return mCaptureOnlyBitmap;
		}

		private void clearLastBitmap() {
			if (mCaptureOnlyBitmap != null) {
				mCaptureOnlyBitmap.recycle();
				mCaptureOnlyBitmap = null;
			}
		}
	}

	// 合成大头贴图片
	private Bitmap createStickerImage(Bitmap bmpImage, Bitmap bmpSticker) {
		// Consider the case of bmpSticker null
		if (bmpSticker == null)
			return bmpImage;
		int bmpImageWidth = bmpImage.getWidth();
		int bmpImageHeight = bmpImage.getHeight();
		Bitmap newbmp = Bitmap.createBitmap(bmpImageWidth, bmpImageHeight,
				Config.ARGB_8888);

		Canvas canvas = new Canvas(newbmp);

		if (name.equalsIgnoreCase("false")) {
			bmpSticker = ImgUtil.AbsResizeBitmap(bmpSticker, 640, 480);
			canvas.drawBitmap(bmpImage, 0, 0, null);
			canvas.drawBitmap(bmpSticker, 0, 0, null);
			canvas.save(Canvas.ALL_SAVE_FLAG);
		} else {
			int x = stickerPhoto.x1;
			int y = stickerPhoto.y1;
			canvas.drawBitmap(bmpImage, 0, 0, null);
			canvas.drawBitmap(bmpSticker, x, y, null);
			canvas.save(Canvas.ALL_SAVE_FLAG);
		}
		return newbmp;
	}

	// 回收信号
	private final class ShutterCallback implements
			android.hardware.Camera.ShutterCallback {
		public void onShutter() {

		}
	}

	private final class RawPictureCallback implements PictureCallback {
		public void onPictureTaken(byte[] data, Camera camera) {
			mRawPictureCallbackTime = System.currentTimeMillis();
		}
	}

	// 实现对照相数据进行处理的方法
	private final class JpegPictureCallback implements PictureCallback {
		public void onPictureTaken(byte[] data, Camera camera) {
			if (temp == false) {
				Bitmap bmpSticker = BitmapFactory.decodeResource(
						CameraSticker.this.getResources(), R.drawable.frame_3);
				bmpScaleSticker = ImgUtil.AbsResizeBitmap(bmpSticker,
						intScreenX, intScreenY);
			} else {
				Bitmap bmpSticker = ImgUtil.Bytes2Bimap(mbyte);
				bmpScaleSticker = ImgUtil.AbsResizeBitmap(bmpSticker,
						intScreenX, intScreenY);
			}
			Log.d(TAG, "JpegPictureCallback");

			if (data != null) {
				Log.d(TAG, "JpegPictureCallback" + data);
				mImageCapture.storeImage(data, camera);
			}
			Log.d(TAG, "Photo");
			// Photo be taken
			mStatus = SNAPSHOT_COMPLETED;
			if (mKeepAndRestartPreview) {
				long delay = 1500 - (System.currentTimeMillis() - mRawPictureCallbackTime);
				mHandler.sendEmptyMessageDelayed(RESTART_PREVIEW, Math.max(
						delay, 0));
			}
		}
	}

	private void doSnap() {
		if (mCaptureObject != null) {
			mCaptureObject.onSnap();
		}
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		Log.d(TAG, "onActivityResult");

		switch (resultCode) {

		case RESULT_OK:
			Log.d(TAG, "onActivityResult RESULT_OK");
			// ///修改
			Bundle bundle = new Bundle();
			bundle = data.getExtras();
			name = "false";
			name = bundle.getString("String");
			// ////
			// /如果为不可移动照片
			if (name.equalsIgnoreCase("false")) {
				byte[] bitmapByte = data.getByteArrayExtra("StickerBitmap");
				mbyte = bitmapByte;
				bmpScaleSticker = ImgUtil.Bytes2Bimap(bitmapByte);
				bmpScaleSticker = ImgUtil.AbsResizeBitmap(bmpScaleSticker,
						intScreenX, intScreenY);
				stickerPhoto.setImageBitmap(bmpScaleSticker);
				temp = true;
			} else {
				byte[] bitmapByte = data.getByteArrayExtra("StickerBitmap");
				mbyte = bitmapByte;
				bmpScaleSticker = ImgUtil.Bytes2Bimap(bitmapByte);
				stickerPhoto.setImageBitmap(bmpScaleSticker);
				temp = true;
			}
			break;

		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void surfaceChanged(SurfaceHolder holder, int format, int width,
			int height) {
		Log.d(TAG, "SurfaceChanged");
		boolean preview = holder.isCreating();
		setViewFinder(width, height, preview);
		mCaptureObject = mImageCapture;
	}

	@Override
	public void surfaceCreated(SurfaceHolder holder) {
		Log.d(TAG, "SurfaceCreated");
		mSurfaceHolder = holder;

	}

	@Override
	public void surfaceDestroyed(SurfaceHolder holder) {
		// Camera�Ƿǹ�����Դ��ʹ�������Ҫ�ͷ�
		Log.d(TAG, "SurfaceDestroyed");
		// TODO Auto-generated method stub
		if (mCamera != null) {
			stopPreview();
			closeCamera();
		}
	}

	private final class AutoFocusCallback implements
			android.hardware.Camera.AutoFocusCallback {
		public void onAutoFocus(boolean success, Camera camera) {

		}
	}

	private int calculatePicturesRemaining() {
		mPicturesRemaining = MenuHelper.calculatePicturesRemaining();
		return mPicturesRemaining;

	}

	private void updateStorageHint() {
		mPicturesRemaining = MenuHelper.calculatePicturesRemaining();
		updateStorageHint(mPicturesRemaining);
	}

	private void updateStorageHint(int remaining) {
		String storageText = null;
		if (remaining == MenuHelper.NO_STORAGE_ERROR) {
			String state = Environment.getExternalStorageState();
			if (state == Environment.MEDIA_CHECKING)
				storageText = getString(R.string.preparing_sd);
			else
				storageText = getString(R.string.no_storage);
			Toast.makeText(this, storageText, Toast.LENGTH_LONG).show();
		} else if (remaining < 1) {
			storageText = getString(R.string.not_enough_space);
			Toast.makeText(this, storageText, Toast.LENGTH_LONG).show();
		}
	}

	// 监听系统注册的有关Media相关的事件
	private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
				Log.d(TAG, "ACTION_MEDIA_MOUNTED");
				updateStorageHint(calculatePicturesRemaining());
			} else if (action.equals(Intent.ACTION_MEDIA_UNMOUNTED)
					|| action.equals(Intent.ACTION_MEDIA_CHECKING)) {
				mPicturesRemaining = MenuHelper.NO_STORAGE_ERROR;
				updateStorageHint(mPicturesRemaining);
			} else if (action.equals(Intent.ACTION_MEDIA_SCANNER_STARTED)) {

			} else if (action.equals(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
				updateStorageHint();
			} else if (action.equals(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE)) {

			}
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		// 轨迹球的按钮事件
		case KeyEvent.KEYCODE_DPAD_CENTER:
			Log.d(TAG, "On DPAD CENTER");
			if (event.getRepeatCount() == 0)
				doSnap();
			break;
		case KeyEvent.KEYCODE_BACK:
			if (mStatus == SNAPSHOT_IN_PROGRESS)
				return true;
			if (mViewStatus == CAMERA_PREVIEW_PAGE) {
				relative_startpage.setVisibility(View.VISIBLE);
				relative_camerasticker.setVisibility(View.GONE);
				mViewStatus = START_PAGE;
				// 必须返回，否则将继续执行Super.onKeyDown,这将导致程序退出
				return true;
			}
			break;

		}
		return super.onKeyDown(keyCode, event);
	}

	private boolean ensureCameraDevice() {
		if (mCamera == null) {
			mCamera = android.hardware.Camera.open();
		}
		return mCamera != null;
	}

	protected void onStart() {
		Log.d(TAG, "onStart");
		super.onStart();

	}

	protected void onRestart() {
		super.onRestart();
	}

	protected void onResume() {// We registerReceiver in onResume, so we
								// unregister in onPause
		Log.d(TAG, "onResume");

		// 注册有关SDCARD的相关事件
		IntentFilter intentFilter = new IntentFilter(
				Intent.ACTION_MEDIA_MOUNTED);
		intentFilter.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
		intentFilter.addAction(Intent.ACTION_MEDIA_CHECKING);
		intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
		intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
		intentFilter.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
		intentFilter.addDataScheme("file");
		registerReceiver(mReceiver, intentFilter);
		// restartPreview();

		mAntiBanding = mPrefs.getString("AntiBanding", "auto");
		mWhiteBalance = mPrefs.getString("WhiteBalance", "auto");
		mFocusMode = mPrefs.getBoolean("AutoFocus", true);

		Log.d(TAG, "Camera Parameters(WhiteBalance)" + mWhiteBalance);
		Log.d(TAG, "Camera Parameters(AntiBanding)" + mAntiBanding);
		Log.d(TAG, "Camera Parameters(FocusMode)"
				+ Boolean.toString(mFocusMode));

		mPausing = false;
		mImageCapture = new ImageCapture();
		// restartPreview();
		super.onResume();
	}

	protected void onPause() {
		Log.d(TAG, "onPause");
		unregisterReceiver(mReceiver);
		stopPreview();
		mPausing = true;
		mImageCapture.clearLastBitmap();
		mImageCapture = null;
		super.onPause();
	}

	protected void onStop() {
		Log.d(TAG, "onStop");
		stopPreview();
		closeCamera();
		super.onStop();
	}

	protected void onDestroy() {
		Log.d(TAG, "onDestroy");
		super.onDestroy();
	}

	// 关闭Camera设备，并释放对象
	private void closeCamera() {
		if (mCamera != null) {
			mCamera.release();
			mCamera = null;
			mPreviewing = false;
		}
	}

	// 停止预览
	private void stopPreview() {
		if (mCamera != null && mPreviewing)
			mCamera.stopPreview();

		mPreviewing = false;
	}

	private void setViewFinder(int w, int h, boolean startPreview) {

		Log.d(TAG, "SetViewFinder");
		// if(mPreviewing == false)
		// return;
		if (mSurfaceHolder == null)
			return;
		if (mPausing == true)
			return;
		// Check the Camera opening
		if (!ensureCameraDevice())
			return;

		mViewFinderWidth = w;
		mViewFinderHeight = h;
		if (mOriginalViewFinderHeight == 0) {
			mOriginalViewFinderWidth = w;
			mOriginalViewFinderHeight = h;
		}

		if (startPreview == false)
			return;
		try {
			mCamera.setPreviewDisplay(mSurfaceHolder);
		} catch (IOException e) {
			mCamera.release();
			mCamera = null;
		}

		mParameters = mCamera.getParameters();

		mParameters.setPreviewSize(640, 480);
		mParameters.setPictureSize(640, 480);

		// 根据设置项的设置Camera的参数,SDK提供的文档在1.5版本没有暴露
		//mParameters.set("antibanding", mAntiBanding);
		mParameters.set("whitebalance", mWhiteBalance);
		// 使参数生效
		try {
			mCamera.setParameters(mParameters);
		} catch (IllegalArgumentException e) {

		}
		// 修改
		final long wallTimeStart = SystemClock.elapsedRealtime();
		final long threadTimeStart = Debug.threadCpuTimeNanos();
		final Object watchDogSync = new Object();
		Thread watchDog = new Thread(new Runnable() {
			public void run() {
				int next_warning = 1;
				while (true) {
					try {
						synchronized (watchDogSync) {
							watchDogSync.wait(1000);
						}
					} catch (InterruptedException ex) {
						//
					}
					if (mPreviewing)
						break;

					int delay = (int) (SystemClock.elapsedRealtime() - wallTimeStart) / 1000;
					if (delay >= next_warning) {
						if (delay < 120) {
							Log.e(TAG, "preview hasn't started yet in " + delay
									+ " seconds");
						} else {
							Log.e(TAG, "preview hasn't started yet in "
									+ (delay / 60) + " minutes");
						}
						if (next_warning < 60) {
							next_warning <<= 1;
							if (next_warning == 16) {
								next_warning = 15;
							}
						} else {
							next_warning += 60;
						}
					}
				}
			}
		});

		watchDog.start();

		// if (Config.LOGV)
		Log.v(TAG, "calling mCameraDevice.startPreview");
		try {
			mCamera.startPreview();
		} catch (Throwable e) {
			// TODO: change Throwable to IOException once
			// android.hardware.Camera.startPreview
			// properly declares that it throws IOException.
		}
		mPreviewing = true;

		synchronized (watchDogSync) {
			watchDogSync.notify();
		}
	}

	// 打开图片文件夹
	public void openPictureGallery() {// open HTC album
		// //全盘扫描
		// sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED,
		// Uri.parse("file://"
		// + Environment.getExternalStorageDirectory())));
		// /
		String cn = "com.htc.album.MainActivity";
		String pkg = "com.htc.album";
		Intent intent = new Intent();
		intent.setClassName(pkg, cn);
		startActivity(intent);
	}

	public void openHTCCamera() {// open HTC camera
		Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
		startActivityForResult(intent, GET_IMAGE);
	}

	private void updateSticker() {// Up to the mode to set the sticker
		if (mCameraMode == true)
			stickerPhoto.setImageBitmap(bmpScaleSticker);
		else
			stickerPhoto.setImageBitmap(null);
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		Log.d(TAG, "onTouchEvent");
		if (name.equalsIgnoreCase("true")) {
			Log.d(TAG, "onTouchEvent1");
			stickerPhoto.autoMouse(event);
			return false;
		} else {
			Log.d(TAG, "onTouchEvent2");
			return true;
		}
	}

}